package services.user.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import model.entities.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import services.user.UserService;
import beans.UserVO;
import daos.user.UserAppDAO;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserAppDAO userAppDAO;

    public void insert(UserVO userVO) throws SQLException {
        User user = populate(userVO);

        this.getUserAppDAO().insert(user);
    }

    public void delete(UserVO userVO) throws SQLException {
        User user = populate(userVO);

        this.getUserAppDAO().delete(user);
    }

    public void update(UserVO userVO) throws SQLException {
        User user = populate(userVO);

        this.getUserAppDAO().update(user);
    }

    public List<UserVO> selectAll() throws SQLException {
        return this.populate(getUserAppDAO().selectAll());
    }

    public List<UserVO> selectByName(UserVO userVO) throws SQLException {
        User user = populate(userVO);

        return populate(this.getUserAppDAO().selectByName(user));
    }

    public boolean exist(UserVO userVO) throws SQLException {
        User user = populate(userVO);

        return this.getUserAppDAO().exist(user);
    }

    public User populate(UserVO userVO) {
        User user = new User();

        user.setLogin(userVO.getLogin());
        user.setName(userVO.getName());
        user.setPassword(userVO.getPassword());

        return user;
    }

    public UserVO populate(User user) {
        UserVO userVO = new UserVO();

        userVO.setLogin(user.getLogin());
        userVO.setName(user.getName());
        userVO.setPassword(user.getPassword());

        return userVO;
    }

    private List<UserVO> populate(List<User> users) {
        List<UserVO> usersVO = new ArrayList<UserVO>();

        for (User user : users) {
            usersVO.add(populate(user));
        }
        return usersVO;
    }

    public UserAppDAO getUserAppDAO() {
        return userAppDAO;
    }

    public void setUserAppDAO(UserAppDAO userAppDAO) {
        this.userAppDAO = userAppDAO;
    }
}